import axios from "axios"
import { createAsyncThunk } from "@reduxjs/toolkit"
import AsyncStorage from "@react-native-async-storage/async-storage"

const backendURL = "https://backend-dot-konav2-dev.wl.r.appspot.com"

export const loginUser = createAsyncThunk(
  "auth/login",
  async ({ email, password }: { email: string; password: string }, { rejectWithValue }) => {
    try {
      const config = {
        headers: {
          "Content-Type": "application/json",
        },
      }
      const response = await axios.post(
        // `${backendURL}/api/login`,
        "https://backend-dot-konav2-dev.wl.r.appspot.com/api/login",
        {
          email,
          password,
        },
        config,
      )
      console.log("data", response?.data)
      await AsyncStorage.setItem("email", email)
      return response?.data
    } catch (error) {
      // return custom error message from backend if present
      if (error.response && error.response.data.message) {
        console.log("error", error)
        return rejectWithValue(error.response.data.message)
      } else {
        return rejectWithValue(error.message)
      }
    }
  },
)
